package com.bxg.chanaldemo;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class ServerChanal {
    public static void main(String[] args) throws IOException {
        //1.创建通道
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //2.绑定端口
        serverSocketChannel.bind(new InetSocketAddress(9999));
        //3.设置通道非阻塞
        serverSocketChannel.configureBlocking(false);
        //4.死循环
        while (true){
            //看谁连接我们了
            SocketChannel socketChannel = serverSocketChannel.accept();
            if(socketChannel!=null){
                //说明有客户端连接
                socketChannel.configureBlocking(false);
                //缓冲区
                ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                int len;
                //以通道作为参照物  nio   读进来  写出去   缓冲区
                while ((len=socketChannel.read(byteBuffer))>0){//缓冲区来说是写
                    byteBuffer.flip();//写->读
                    System.out.println(new String(byteBuffer.array(), 0, len));
                    //读->写
                    byteBuffer.clear();
                }
                //读取数据完毕
                //回应
                ByteBuffer byteBuffer1 = ByteBuffer.wrap("欢迎来到博学谷".getBytes());
                socketChannel.write(byteBuffer1);


            }


        }

    }
}
